package secondFragment.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.xuegengwang.xuegengwang.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import common.BaseFragment;
import common.Constant;
import https.InterNetController;
import in.srain.cube.views.ptr.PtrFrameLayout;
import pay.activity.Pay;
import question.activity.QuestionDetail;
import secondFragment.adapter.PqLvAdapter;
import secondFragment.bean.PopularQuestionBean;
import utils.MyLogUtils;
import view.MyPtrRefresh_LoadView;

/**
 * Created by Administrator on 2017/2/18.
 * 热门提问
 */
@SuppressLint("ValidFragment")
public class PopularQuestionFragment extends BaseFragment {
    private View view;
    private MyPtrRefresh_LoadView refreshLayout;
    private ListView listView;
    private PqLvAdapter pqLvAdapter;
    private ArrayList<PopularQuestionBean.ConsultListBean> arrayList;
    private MyReceiver myReceiver;

    private final int ONREFRESH = 0;
    private final int ONLOAD = 1;
    private final int ZAN = 2;
    private int page = 1;
    private static final String TAG = "PopularQuestionFragment";

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS://成功返回
                    if (msg.arg1 != ZAN) {
                        switch (msg.arg1) {
                            case ONREFRESH:
                                Gson gson = new Gson();
                                PopularQuestionBean popularQuestionBean = gson.fromJson((String) msg.obj, PopularQuestionBean.class);
                                if (popularQuestionBean != null) {
                                    List<PopularQuestionBean.ConsultListBean> consultList = popularQuestionBean.getConsultList();
                                    if (consultList != null) {
                                        if (consultList.size() > 0) {
                                            arrayList.clear();
                                            for (int i = 0; i < consultList.size(); i++) {
                                                arrayList.add(consultList.get(i));
                                            }
                                        }
                                        pqLvAdapter.notifyDataSetChanged();
                                    }
                                }
                                refreshLayout.OnRefreshComplete();
                                break;
                            case ONLOAD:
                                Gson gson1 = new Gson();
                                PopularQuestionBean popularQuestionBean1 = gson1.fromJson((String) msg.obj, PopularQuestionBean.class);
                                if (popularQuestionBean1 != null) {
                                    List<PopularQuestionBean.ConsultListBean> consultList = popularQuestionBean1.getConsultList();
                                    if (consultList != null) {
                                        if (consultList.size() > 0) {
                                            for (int i = 0; i < consultList.size(); i++) {
                                                arrayList.add(consultList.get(i));
                                                pqLvAdapter.notifyDataSetChanged();
                                            }
                                        } else {
                                            page--;
                                        }
                                    }
                                }
                                refreshLayout.OnRefreshComplete();
                                break;
                            default:
                                break;
                        }
                    } else {
                        try {
                            JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                            String err_code = jsonObject.getString("err_code");
                            if ("0".equals(err_code)) {
                                //赞
                                String praise = arrayList.get(msg.arg2).getPraise();
                                int i = Integer.parseInt(praise) + 1;
                                arrayList.get(msg.arg2).setPraise(String.valueOf(i));
                                arrayList.get(msg.arg2).setIs_prised(1);
                            } else {
                                //取消赞
                                String praise = arrayList.get(msg.arg2).getPraise();
                                int i = Integer.parseInt(praise) - 1;
                                arrayList.get(msg.arg2).setPraise(String.valueOf(i));
                                arrayList.get(msg.arg2).setIs_prised(0);
                            }
                            pqLvAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    break;
                case Constant.ERROR_CODE_FAILD:
                    if (refreshLayout != null) {
                        refreshLayout.OnRefreshComplete();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.popular_question_fragment, container, false);
        if (getMyActivity() != null) {
            initView();
            registerReceiver();
            GetDataFromInterNet(page = 1, ONREFRESH);
        }
        return view;
    }

    private void initView() {
        refreshLayout = (MyPtrRefresh_LoadView) view.findViewById(R.id.pq_refreshLayout);
        listView = (ListView) view.findViewById(R.id.pq_lv);
        arrayList = new ArrayList<>();
        pqLvAdapter = new PqLvAdapter(getMyActivity(), arrayList, new PqLvAdapter.onPayClick() {
            @Override
            public void click(int position) {
                if ((getMyActivity().hasLoad())) {
                    Intent i = new Intent(getMyActivity(), Pay.class);
                    i.putExtra("dialog_id", arrayList.get(position).getDialogid());
                    i.putExtra("position", position);
                    i.putExtra("price", Constant.QUESTIONWATCH_PRICE);
                    i.putExtra("payType", Constant.QUESTIONWATCH);
                    startActivityForResult(i, 1);
                } else {
                    getMyActivity().login(getMyActivity());
                }
            }
        }, new PqLvAdapter.PraiseListener() {
            @Override
            public void praiseListener(int position) {
                praise(position);
            }
        }, new PqLvAdapter.OnQuestionDetailListener() {
            @Override
            public void onQuestionDetailListener(int position) {
                Intent i = new Intent(getMyActivity(), QuestionDetail.class);
                i.putExtra("dialogId", arrayList.get(position).getDialogid());
                startActivityForResult(i, position);
            }
        });
        listView.setAdapter(pqLvAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            }
        });
        refreshLayout.setMyPtrHandler(new MyPtrRefresh_LoadView.MyPtrHandler() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                GetDataFromInterNet(++page, ONLOAD);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                GetDataFromInterNet(page = 1, ONREFRESH);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MyLogUtils.e(TAG, resultCode + "....");
        if (resultCode != Activity.RESULT_CANCELED) {
            switch (resultCode) {
                case Constant.PAY_SUCCESS:
                    int position = data.getIntExtra("position", 0);
                    arrayList.get(position).setIspay("1");
                    String watch = arrayList.get(position).getWatch();
                    if (watch != null && !TextUtils.isEmpty(watch)) {
                        Integer integer = Integer.parseInt(watch);
                        int i = integer.intValue() + 1;
                        arrayList.get(position).setWatch("" + i);
                    } else {
                        arrayList.get(position).setWatch("1");
                    }
                    pqLvAdapter.notifyDataSetChanged();
                    Intent i = new Intent(getMyActivity(), QuestionDetail.class);
                    i.putExtra("dialogId", arrayList.get(position).getDialogid());
                    i.putExtra("type", "hot");
                    i.putExtra("state", "正常");
                    startActivity(i);
                    break;
                case 1:
                    //问题状态改变了
                    int zan1 = data.getIntExtra("zan", 0);
                    int comment1 = data.getIntExtra("comment", 0);
                    boolean isPraised1 = data.getBooleanExtra("isPraised", false);
                    boolean hasPay = data.getBooleanExtra("hasPay", false);
                    if (hasPay) {
                        arrayList.get(requestCode).setIspay("1");
                    } else {
                        arrayList.get(requestCode).setIspay("0");
                    }
                    arrayList.get(requestCode).setComment(String.valueOf(comment1));
                    arrayList.get(requestCode).setPraise(String.valueOf(zan1));
                    if (isPraised1) {
                        arrayList.get(requestCode).setIs_prised(1);
                    } else {
                        arrayList.get(requestCode).setIs_prised(0);
                    }
                    pqLvAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getMyActivity().unregisterReceiver(myReceiver);
    }

    private void registerReceiver() {
        myReceiver = new MyReceiver();
        getMyActivity().registerReceiver(myReceiver, new IntentFilter(Constant.ACTION_LOGIN));
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            GetDataFromInterNet(page = 1, ONREFRESH);
        }
    }

    private void GetDataFromInterNet(int page, int flag) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page", String.valueOf(page));
        new InterNetController(getMyActivity(), Constant.CONSULT, myHandler, hashMap, flag, false);
    }

    private void praise(int position) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("dialog_id", arrayList.get(position).getDialogid());
        new InterNetController(getMyActivity(), Constant.DIALOGPRISE, myHandler, hashMap, ZAN, position, false);
    }

}
